from django.urls import reverse
from django.conf import settings
from django.http import QueryDict
from django.template import Library
from django.utils.safestring import mark_safe

register = Library()


def check_permission(request, name):
    # print(request, name, args, kwargs)
    # 1.获取当前登录用户的角色
    role = request.nb_user.role

    # 2.根据角色获取他所有的权限字典
    permission_dict = settings.NB_PERMISSION[role]
    if name in permission_dict:
        return True

    if name in settings.NB_PERMISSION_PUBLIC:
        return True


@register.simple_tag
def add_permission(request, name, *args, **kwargs):
    """
    按钮显示
    1. 获取当前登录的用户所属的角色
    2. 从settings中获取角色的权限字典NB_PERMISSION
    3. 判断是否有该权限 name
        - 有，生成并返回该按钮
            <a href="{% url %}" class="btn btn-success"><span class="glyphicon glyphicon-plus-sign"></span></a>

        - 无，返回空
    """
    if not check_permission(request, name):
        return ''
    url = reverse(name, args=args, kwargs=kwargs)
    tpl = mark_safe(f'''
    <a href="{url}" class="btn btn-success"><span class="glyphicon glyphicon-plus-sign"></span>新建</a>
    ''')
    return tpl


@register.simple_tag
def edit_permission(request, name, *args, **kwargs):
    """
    按钮显示
    1. 获取当前登录的用户所属的角色
    2. 从settings中获取角色的权限字典NB_PERMISSION
    3. 判断是否有该权限 name
        - 有，生成并返回该按钮
            <a href="{% url %}" class="btn btn-success"><span class="glyphicon glyphicon-plus-sign"></span></a>

        - 无，返回空
    """
    if not check_permission(request, name):
        return ''
    url = reverse(name, args=args, kwargs=kwargs)
    param = request.GET.urlencode()
    if param:
        new_query_dict = QueryDict(mutable=True)
        new_query_dict['_filter'] = param
        filter_string = new_query_dict.urlencode()
        tpl = mark_safe(f'''
        <a href="{url}?{filter_string}" class="btn btn-primary btn-xs">编辑</a>
        ''')
    else:
        tpl = mark_safe(f'''
        <a href="{url}" class="btn btn-primary btn-xs">编辑</a>
        ''')

    return tpl


@register.simple_tag
def delete_permission(request, name, cid, *args, **kwargs):
    if not check_permission(request, name):
        return ''

    tpl = mark_safe(f'''
    <a cid="{cid}" class="btn btn-danger btn-xs btn-delete">删除</a>
    ''')
    return tpl


@register.simple_tag
def delete_url_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ''
    url = reverse(name, args=args, kwargs=kwargs)
    tpl = mark_safe(f'''
    <a href="{url}" class="btn btn-danger btn-xs">删除</a>
    ''')
    return tpl


@register.filter
def has_permission(request, others):
    name_list = others.split('.')
    status = False
    for name in name_list:
        status = True
        if check_permission(request, name):
            return True

    if status:
        return True
    return False
